package com.handinfo.uimenu.window;

import java.io.DataInputStream;
import java.util.Hashtable;
import javax.microedition.lcdui.Graphics;

import com.handinfo.engine.AbstractGameScreen;
import com.handinfo.engine.GameManager;
import com.handinfo.uimenu.UIAbstractWindow;
import com.handinfo.uimenu.UIManager;
import com.handinfo.uimenu.UITools;
import com.handinfo.uimenu.UIWindowFactory;
import com.handinfo.util.Tools;
import com.test.touch.GameTouchManager;
import com.test.touch.TouchListener;
import com.test.touch.TouchRect;

public class UIAnnouncement extends UIAbstractWindow
{
	
	private static final int WORD_W = UITools.IW_RECTS;//单元列间距
	private static final int WORD_H = UITools.IH_RECTS;//单元行间距
	private static final int LIST_RECT_H = AbstractGameScreen.FONT_H; //单元列表的高
	private static final int WordColour = 0xFFFFFF;
	private static final int TitleColour = 0xFFFF00;//标题公告的信息
	private static final int InfosColour = 0x4eff5c;//选择项的颜色
	private static final int TITLE_MAXLINE = 5;//标题最大行数
	private static final int TITLE_H = LIST_RECT_H * TITLE_MAXLINE + 2*WORD_H;//标题公告信息框的高
	private static final int LIST_H = (UITools.H_RECT - TITLE_H - 2*WORD_H);//列表实际高
	private static final int LIST_NUMBER = (LIST_H - 2*WORD_H)/UITools.H_PRE;//一页最大单元列表的行数
	private static final int DRAG_H = LIST_H;
	private static final int m_w_content = UITools.W_RECT;//上框的宽
	private static final int m_w_contentd = m_w_content - 15;//下框的宽
	
	private int m_page_num = 1;//总页数
	private int m_page_index = 0;//当前页数从0开始算
	private int m_line_index;//当前行索引
	private int m_plan = 0;//滚动百分比
	private byte m_num = 1;//绘制内容框数量
	private final String m_name = "游戏公告";
	private String[] m_title;//公告布信息
	private String[] m_infos;//公告选择项
	private int m_title_h;//滚动变量
	private int m_title_maxh;//滚动最大量
	private boolean m_title_run;//是否滚动标题
	private int m_index;//当前内容索引
	private byte m_state;//状态
	private String[] m_specificinfos;//具体公告信息
	private static final int INFOS_NUMBER = (UITools.H_RECT - 2*WORD_H)/LIST_RECT_H;//具体公告的一页组大单元行数
	private int m_page_num_infos = 1;//总页数
	private int m_page_index_infos = 0;//当前页数从0开始算
	
	public UIAnnouncement(int id)
	{
		super(id);
		setBounds(UITools.X_BG, UITools.Y_BG, UITools.W_BG, UITools.H_BG);
//		initTouch();
	}
	
		
//	protected void onTouchFocusChange(boolean focus) {
//		if (focus) {
//			initTouch();
//		}
//	}


	private void init(){
		if( m_title != null ){
			int size = m_title.length;
			if( size > TITLE_MAXLINE ){
				m_title_h = -(TITLE_H >> 1);
				m_title_run = true;
				m_title_maxh = size*LIST_RECT_H;
			}
		}
		if( m_infos != null ){
			int size = m_infos.length;
			int num = 0;
			m_page_num = 0;
			m_page_index = 0;
			num = size%LIST_NUMBER;
			if( num > 0 ){
				m_page_num ++;
			}
			m_page_num += size/LIST_NUMBER;	
		}
	}
	
	private void setContent()
	{
		if( m_specificinfos != null ){
			int size = m_specificinfos.length;
			int num = 0;
			m_page_num_infos = 0;
			m_page_index_infos = 0;
			num = size%INFOS_NUMBER;
			if( num > 0 ){
				m_page_num_infos ++;
			}
			m_page_num_infos += size/INFOS_NUMBER;
		}
		Tools.debugPrintln("m_page_num_infos="+m_page_num_infos);
	}
	
	protected void paintContent(Graphics g)
	{
		//绘制内容
		if( m_state != 0 ){
			//绘制背景
			UITools.paintBackGround(g, m_x, m_y, m_w, m_h, m_name,false,true);
			paintspecificinfos(g);
		}else{
			//绘制背景
			UITools.paintBackGround(g, m_x, m_y, m_w, m_h, m_name,true,true);
			paintInfos(g);
		}
	}
    
	/** 绘制主状态 */
	private void paintInfos(Graphics g){
		int tempX = m_x + UITools.INITX_CONTENT;
		int tempY = m_y + UITools.INITY_CONTENT;
		//绘制上框
		UITools.paintContentRect(g, tempX, tempY, m_w_content, TITLE_H);
		//绘制上框内容
		if( m_title != null ){
			g.setColor(TitleColour);
			tempX = m_x + UITools.INITX_CONTENT + 2*WORD_W;
			tempY = m_y + UITools.INITY_CONTENT + WORD_H;
			g.setClip(tempX, tempY, m_w_content, TITLE_H - 2*WORD_H);
			for( int i=0;i<m_title.length;i++ ){
				g.drawString(m_title[i], tempX, tempY+i*LIST_RECT_H - m_title_h, 0);
			}
		}
		
		//绘制下框
		g.setClip(0, 0, AbstractGameScreen.SCREEN_WIDTH, AbstractGameScreen.SCREEN_HEIGHT);
		tempX = m_x + UITools.INITX_CONTENT;
		tempY = m_y + UITools.INITY_CONTENT + TITLE_H + WORD_H;
		UITools.paintContentRect(g, tempX, tempY, m_w_contentd, LIST_H);
		
		//绘制下框内容
		g.setClip(tempX, tempY + WORD_H, m_w_content, LIST_NUMBER * UITools.H_PRE);
		if( m_infos != null ){
			tempX = m_x + UITools.INITX_CONTENT + WORD_W;
			tempY = m_y + UITools.INITY_CONTENT + TITLE_H + 2*WORD_H;
			UITools.drawSelectBox(g, tempX, tempY + (m_line_index*UITools.H_PRE),m_w_contentd - 2*WORD_W, UITools.H_PRE);
		
			tempX = m_x + UITools.INITX_CONTENT + 2*WORD_W;
			tempY = m_y + UITools.INITY_CONTENT + TITLE_H + 2*WORD_H;
			g.setColor(InfosColour);
			for( int i= m_page_index*LIST_NUMBER;i<m_infos.length;i++ ){
				g.drawString(m_infos[i], tempX, tempY + (i-m_page_index*LIST_NUMBER)*UITools.H_PRE, 0);
			}
		}

		//绘制滑动滚轴
		tempX = m_x + UITools.X_DRAG;
		tempY = m_y + UITools.INITY_CONTENT + TITLE_H + 2*WORD_H;
		UITools.paintScrollBar(g, tempX, tempY, DRAG_H, m_plan);

	}
	
	/** 绘制子状态 */
	protected void paintspecificinfos(Graphics g)
	{
		int tempX = m_x + UITools.INITX_CONTENT;
		int tempY = m_y + UITools.INITY_CONTENT;
		if( m_specificinfos != null ){
			g.setClip(tempX, tempY, m_w_content, INFOS_NUMBER*LIST_RECT_H);
			specialString(g, tempX, tempY, m_specificinfos, WordColour);
		}
		
		//绘制翻页
		if (m_page_num_infos > 1 ) {
			UITools.paintPage(g, m_x + (m_w >> 1), m_y + m_h - 12, m_page_index_infos, m_page_num_infos,true,true);
		}
	}
	
	//绘制带颜色数字字符串
	protected void specialString(Graphics g,int x,int y,String[] Str,int WordColour){
		if( Str != null ){
			int num = 0;
			for(int h=0;h<Str.length;h++){
				int size = Str[h].length();
				int width = 0;
				for(int i=0;i<size;i++){
					String key = ""+(i+num);
					if( datas.containsKey(key)){
						String a = (String)datas.get(key);
						int colour = Integer.parseInt(a);
						g.setColor(colour);
					}else{
						g.setColor(WordColour);
					}
					char temp = Str[h].charAt(i);
					g.drawChar(temp, x+width, y+(h-INFOS_NUMBER*m_page_index_infos)*LIST_RECT_H, 0);
					width += AbstractGameScreen.s_font.charWidth(temp);
					key = null;
						
				}
				num += size;
			}

		}
	} 
	
	protected static final String MARK_F = "<mark c=";
	protected static final String MARK_B = "</mark>";
	protected static final char SIGN = '>';
	protected static final String COLOUR = "000000";
	protected static Hashtable datas = new Hashtable();	
	
	public String cutString(String _temp){
		if( _temp == null ){
			return null;
		}
		String temp = _temp;
		StringBuffer buff = new StringBuffer();
		datas.clear();
	    int index = 0;//标签的位置索引
	    int lastindex = 0;//标签结束的位置索引
	    int size = temp.length();
	    int num = 0;//记录循环次数
	    int markf_size = MARK_F.length();
	    int markb_size = MARK_B.length();
	    int colour_size = COLOUR.length();
	    int sign_size = 1;
	    while( (index = temp.indexOf(MARK_F, lastindex)) != -1 ){
	    	    Tools.debugPrintln("index="+index);
	    	    int a = index+markf_size;//颜色值的起始
	    	    int a1 = temp.indexOf(SIGN, a);//颜色结束符位置
	    	    buff.append(temp.substring(lastindex, index));
	    	    Tools.debugPrintln("buff="+buff.toString());
	            Tools.debugPrintln("a1="+a1);	    	   
	    	    if( a1 != -1 ){
		    	    lastindex = temp.indexOf(MARK_B, a1);
		    	    int length = lastindex - a1 - 1;	   
		    	    String str = "" + Integer.parseInt(temp.substring(a, a1),16);//颜色
		    	    int charth = 0;
		    	    int w = temp.substring(0,index).indexOf(Tools.CHANGE_ROW);
		    	    while( w != -1){
		    	    	   charth ++;
		    	    	   if( w < index ){
			    	    	   w = temp.substring((w+1),index).indexOf(Tools.CHANGE_ROW); 
		    	    	   }else{
		    	    		   w = -1;
		    	    	   }	    	    	   
		    	    }
		    	    Tools.debugPrintln("charth="+charth);
		    	    for(int i=0;i<length;i++){
		    	    	String key = "" + (index - num*(markf_size + colour_size + sign_size + markb_size) + i - charth);//位置
		    	    	datas.put(key, str);
		    	    	Tools.debugPrintln("key="+key+";str="+str);
		    	    } 	    	
	    	    	    
	    	    }
	    	    Tools.debugPrintln("lastindex="+lastindex);
	    	    if( lastindex != -1 ){
	    	    	buff.append(temp.substring((a1+1),lastindex));
	    	    	lastindex += markb_size;
	    	    	num ++;
	    	    }	  
	    }
	    if( lastindex < size ){
	    	buff.append(temp.substring(lastindex, size));
	    }
	    String a = buff.toString();
	    Tools.debugPrintln("a="+a);
	    buff = null;
	    return a;
	}
	
	protected void checkIndex(){
		m_index = m_page_index*LIST_NUMBER + m_line_index;
	}
	
	protected void checkDragPlan(){
		int max = m_num <= 1?2:m_num;
	    m_plan = m_index*100/(max-1);
	}
	
	protected void registerTouch() {
		super.registerTouch();
		
		registerNormalSoft(true, true);
		initTouchRect(state0NormalRect);
		state0ListRect = new int[LIST_NUMBER][];
		for(int i=0;i<LIST_NUMBER;i++) {
			state0ListRect[i] = new int[]{20,129+UITools.H_PRE*i,410,UITools.H_PRE};
		}
		initTouchRect(state0ListRect);
	}


	protected void onTouchRect(int[][] rect,int touchid) {
		switch(m_state) {
		case 0:
			if (rect == state0ListRect) {
				m_line_index = touchid;
				checkIndex();
				checkDragPlan();
				GameTouchManager.keyPressedFire();
			} else if (rect == state0NormalRect) {
				if (touchid == 0) {
					GameTouchManager.keyPressedDir(1);
				} else {
					GameTouchManager.keyPressedDir(3);
				}
			}
			break;
		}
	}
	
	private int[][] state0ListRect;
	private int[][] state0NormalRect = new int[][]{
			///上下拉
			{444,124,24,36},
			{444,236,24,36},
	};
	
	protected void keyLogic()
	{
		 titlerun();
		 switch(m_state){
			 case 0:
				 if( AbstractGameScreen.haveKeyPressed( AbstractGameScreen.GK_UP ) ){
						 if( m_line_index > 0 ){
								m_line_index --;
							}else{
								if( m_page_index > 0 ){
									m_page_index --;
									m_line_index = LIST_NUMBER -1;
								}
							}
							checkIndex();
							checkDragPlan();
				}else if( AbstractGameScreen.haveKeyPressed( AbstractGameScreen.GK_DOWN ) ){
					if( m_line_index < LIST_NUMBER - 1){
						if( m_index < m_num -1){
							m_line_index ++;
						}
					}else{
						if( m_page_index < m_page_num - 1){
							m_page_index ++;
							m_line_index = 0;
						}
					}
					checkIndex();
					checkDragPlan();
				}
				else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_LEFT_SOFT)
						|| AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_A)) {
						 GameManager.getInstance().m_game_message.sendGameNoticeInfo((byte)m_index);
						 
						 clearAllRects();
						 registerNormalSoft(false, true);
						 
				}else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_RIGHT_SOFT)) {
						close();
				}
				 break;
			 case 1:
				 if( AbstractGameScreen.haveKeyPressed( AbstractGameScreen.GK_LEFT ) ){
				        if( m_page_index_infos > 0 ){
				        	m_page_index_infos --;
				        }   	
				}
				else if( AbstractGameScreen.haveKeyPressed( AbstractGameScreen.GK_RIGHT ) ){
				        if( m_page_index_infos < m_page_num_infos - 1){
				        	m_page_index_infos++;
				        }   	
				}
	            else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_RIGHT_SOFT)) {
				 	   	m_state = 0;
				 	   clearAllRects();
				 	  registerTouch();
				}
				break;
		 }
		 
	}
	
	public void titlerun(){
		if( m_state == 0 ){
			if( m_title_run ){
				if( m_title_h < m_title_maxh ){
					m_title_h++;
				}else{
					m_title_h = - TITLE_H;
				}
			}
		} 
	}
	
	/**
	 * 接收公告提示
	 * */
	public static final void recvAnnouncement(DataInputStream dis)
	{
		try {
			Tools.debugPrintln("recvAnnouncement");
		  	UIAnnouncement win = (UIAnnouncement)UIWindowFactory.createWindow(UIWindowFactory.WINDOW_ID_ANNOUNCEMENT);
		  	if( win != null ){
		  		win.m_state = 0;
		  		String temp = dis.readUTF();
		  		win.m_title = Tools.getStrArray(temp, m_w_content - 4*WORD_W);
		  		byte size = dis.readByte();	
		  		Tools.debugPrintln("size="+size);
		  		if( size == 0 ){
		  			win = null;
		  			return;
		  		}
		  		win.m_num = size;
		  		win.m_infos = new String[size];
				for( int i=0;i<size;i++){
                     win.m_infos[i] = (i+1)+"."+dis.readUTF();
				}
				win.init();
		  	}
		  	UIManager.getInstance().addWindow(win);
		}
		catch (Exception e) {
			Tools.debug(e);
		}
	}
    
	/** 公告内容 */
	public static final void recvAnnouncementInfos(DataInputStream dis)
	{
		try {
			Tools.debugPrintln("recvAnnouncementInfos");
		  	UIAnnouncement win = (UIAnnouncement)UIManager.getInstance().getWindowById(UIWindowFactory.WINDOW_ID_ANNOUNCEMENT);
		  	if( win != null ){
		  		win.m_state = 1;
		  		String temp = dis.readUTF();
				win.m_specificinfos = Tools.getStrArray(win.cutString(temp),UITools.W_CONTENT);
				win.setContent();
		  	}
		  	GameManager.getInstance().m_game_message.unlockNetwork();
		}
		catch (Exception e) {
			GameManager.getInstance().m_game_message.unlockNetwork();
			Tools.debug(e);
		}
	}
}
